<?php
namespace app\common\library;
/**
 * 1688开放平台签名生成工具 (分销严选专用)
 */
class AlibabaSignatureGenerator {
    public string $url = 'https://gw.open.1688.com/openapi/';
    public string  $appKey = '1402148';
    public string  $appSecret ='heYQz0AdJ9';

    public string $apiInfo = '';
    public string $accessToken = '';

    public function __construct($apiInfo,$accessToken) {
        $this->apiInfo = $apiInfo.$this->appKey;
        $this->accessToken = $accessToken;
    }

    /**
     * 发送请求获取数据
     * @param $codeArr
     * @return mixed
     */
    public function sendData($codeArr){
        $aliParams = array();
        $codeArr['access_token'] = $this->accessToken;
        $str = '';
        foreach ($codeArr as $key => $val) {
            $aliParams[] = $key . $val;
            $str .= $key .'='.$val.'&';
        }
        sort($aliParams);
        $sign_str = join('', $aliParams);
        $sign_str = $this->apiInfo . $sign_str;

        $_aop_signature = strtoupper(bin2hex(hash_hmac("sha1", $sign_str, $this->appSecret, true)));
        $str .='&_aop_signature='.$_aop_signature;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->url.$this->apiInfo);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);

        curl_setopt($ch, CURLOPT_FAILONERROR, false);

        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/x-www-form-urlencoded']);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $str);
        curl_setopt($ch, CURLOPT_POST, 1);

//        echo "Start to run...\n";
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }
}